package day31;

import java.io.*;
import java.net.*;

/**
 * 简化版服务器端程序
 * 实现基本的Socket服务器功能，监听客户端连接并进行通信
 */
public class Server {
    // 服务器端口
    private static final int PORT = 8888;
    
    public static void main(String[] args) {
        System.out.println("服务器启动中...");
        
        // 创建服务器Socket
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，监听端口: " + PORT);
            
            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());
                
                // 为每个客户端创建一个线程处理通信
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clientHandler.start();
            }
        } catch (Exception e) {
            System.out.println("服务器发生错误");
        } finally {
            // 关闭服务器Socket
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e) {
                // 忽略关闭时的异常
            }
        }
    }
    
    /**
     * 客户端处理线程
     * 用于处理单个客户端的通信请求
     */
    static class ClientHandler extends Thread {
        private Socket clientSocket;
        
        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }
        
        public void run() {
            PrintWriter out = null;
            BufferedReader in = null;
            
            try {
                // 创建输入输出流
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                
                // 向客户端发送欢迎消息
                out.println("欢迎连接到服务器！");
                
                String inputLine;
                // 读取客户端发送的消息并回显
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("收到客户端消息: " + inputLine);
                    
                    // 如果客户端发送"bye"则关闭连接
                    if ("bye".equals(inputLine)) {
                        out.println("服务器已断开连接");
                        break;
                    }
                    
                    // 回显客户端消息
                    out.println("服务器收到: " + inputLine);
                }
            } catch (Exception e) {
                System.out.println("处理客户端时发生错误");
            } finally {
                // 关闭连接
                try {
                    System.out.println("客户端断开连接: " + clientSocket.getInetAddress().getHostAddress());
                    if (in != null) in.close();
                    if (out != null) out.close();
                    if (clientSocket != null) clientSocket.close();
                } catch (Exception e) {
                    // 忽略关闭时的异常
                }
            }
        }
    }
}